<?php


namespace app\common\cachemodel;


use app\common\lib\Util;
use app\common\model\BaseCache;
use think\Exception;
use XznsTools\cache\CacheManage;

class ZlVipRanking extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_vip_ranking';

    protected $cacheModel = 'vip.ranking';

    /**
     * 获取排行榜信息
     * @param $userInfo
     * @param bool $isGetUserAdorn 是否获取用户的装扮，默认不获取
     * @return array|mixed
     * @throws \Exception
     */
    public function getVipRankingList($userInfo, bool $isGetUserAdorn = false)
    {
        $page = input('page/d', 1);
        $data = $this->getListPage('everyday', 'ranking', [], 0, 'asc', 0);

        $userModel = new \app\common\model\User();
        foreach ($data['data'] as $key => $v)
        {
            try
            {
                $user = $userModel->getUserinfo(['id' => $v['uid']]);
            }
            catch (\Exception $e)
            {
                $user = null;
            }
            $data['data'][$key]['avatar'] = $user['avatar'] ?? '';
            $data['data'][$key]['nickname'] = $user['nickname'] ?? '匿名';

            if ($isGetUserAdorn)
            {
                $adorn = Util::getUserAdorn($v['uid']);
                $data['data'][$key]['avatar_adorn'] = $adorn['avatar_adorn'];
                $data['data'][$key]['badge'] = ['https://oss.goddessxzns.com/vip/images/vip_center/lucky/badge_vip' . $v['vip_level'] . '.png'];
            }
        }

        if ($page == 1)
        {   // 获取自己星力值信息
            $vipInfo = (new ZlUserVip())->getInfoById($userInfo['id']);

            $my_data = [
                'avatar' => $userInfo['avatar'],
                'nickname' => $userInfo['nickname'],
                'star_num' => (int)$vipInfo['star_num'],
                'ranking' => $this->getUserRanking($userInfo['id']),
                'vip' => (int)$vipInfo['vip_level'],
            ];

            if ($isGetUserAdorn)
            {
                $adorn = Util::getUserAdorn($userInfo['id']);
                $adornArr = [];
                $adornArr['avatar_adorn'] = $adorn['avatar_adorn'];
                $adornArr['badge'] = ['https://oss.goddessxzns.com/vip/images/vip_center/lucky/badge_vip' . $vipInfo['vip_level'] . '.png'];
                $data['my_data'] = array_merge($my_data, $adornArr);
            } else
            {
                $data['my_data'] = $my_data;
            }
        }

        $data['data'] = $this->listDataReset($data['data']);

        return $data;
    }

    /**
     * 排行榜数据格式重组
     * @param array $listData
     * @return array
     */
    public function listDataReset(array $listData)
    {
        $data = [];
        foreach ($listData as $itemDAta)
        {
            $item = [
                'avatar' => $itemDAta['avatar'],
                'nickname' => $itemDAta['nickname'],
                'star_num' => (int)$itemDAta['star_num'],
                'vip' => (int)$itemDAta['vip_level'],
                'ranking' => (int)$itemDAta['ranking'],
            ];
            if (isset($itemDAta['avatar_adorn']) && isset($itemDAta['badge']))
            {
                $data[] = array_merge($item, ['avatar_adorn' => $itemDAta['avatar_adorn'], 'badge' => $itemDAta['badge']]);
            } else
            {
                $data[] = $item;
            }
        }

        return $data;
    }

    /**
     * 分页数据重写
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->whereIn('vr.id', $ids);
            } else
            {
                $this->where(function ($query)
                {   // 今日的排行榜信息和虚拟用户
                    $query->where('vr.create_time', strtotime(date('Ymd')))->whereOr('vr.is_virtual', 1);
                });
            }

            $rankingList = $this->alias('vr')
                ->order('vr.star_num desc,vr.star_num_time asc')
                ->limit(200)
                ->field('vr.id,vr.uid,vr.star_num,vr.vip_level,vr.create_time')->select();
            $rankingList = json_decode(json_encode($rankingList), true);
            $data = [];
            foreach ($rankingList as $key => $value)
            {
                $value['ranking'] = $key + 1;
                $data[$value['uid']] = $value;
            }

        }

        catch (Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    /**
     * 未开启缓存从数据库获取分页数据
     * @param array $type 分页数据状态
     * @param string $sortType 排序方式
     * @return array
     */
    public function getPaginateInData($type, $sortType)
    {
        try
        {
            $this->where(function ($query)
            {   // 今日的排行榜信息和虚拟用户
                $query->where('vr.create_time', strtotime(date('Ymd')))->whereOr('vr.is_virtual', 1);
            });

            $rankingList = $this->alias('vr')
                ->order('vr.star_num desc,vr.star_num_time asc')
                ->field('vr.id,vr.uid,vr.star_num,vr.vip_level,vr.create_time')->paginate()->toArray();
            $data = [];
            foreach ($rankingList['data'] as $key => $value)
            {
                $value['ranking'] = ($rankingList['per_page'] * ($rankingList['current_page'] - 1)) + $key + 1;
                $data[$value['uid']] = $value;
            }
            $rankingList['data'] = $data;
        }

        catch (Exception $e)
        {
            $rankingList = [];
        }

        return $rankingList;
    }

    /**
     * 获取用户当前排行
     * @param $uid
     * @return string
     * @throws \Exception
     */
    public function getUserRanking($uid)
    {
        $rankingList = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, 'everyday')
            ->setPage(-1)
            ->setListKeyType(0)// 类型 用于分页 例如 0全部 1待支付 已支付 //
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc')
            {
                if ($isCache)
                { // 开启了缓存
                    return $this->getInfoByIdsInData([], [], $sortType);
                } else
                { // 没开启缓存
                    return $this->getPaginateInData([], $sortType);
                }
            }, 'ranking', 0);

        if (isset($rankingList['data'][$uid]))
        {
            $ranking = (int)$rankingList['data'][$uid];
        } else
        {
            $ranking = '200+';
        }

        return (string)$ranking;
    }

    /**
     * 删除用户排行榜信息
     * @param int $uid
     * @throws \Exception
     */
    public function deleteRanking(int $uid): void
    {
        // 删除数据库用户排行榜信息
        $this->where('uid', $uid)->delete();

        CacheManage::getInstance()->setCacheConfig($this->cacheModel, 'everyday')->setListKeyType(0)->rmCache('list');
    }
}
